import {
  routes,
  routerMap
} from '@/router/routers'

const state = {
  routers: routes,
  hasGetRules: false
}

const mutations = {
  CONCAT_ROUTES (state, routerList) {
    state.routers = routerList.concat(routes)
    state.hasGetRules = true
    localStorage.setItem('accessRouters', state.routers)
    // console.log(JSON.parse(localStorage.getItem('accessRouters')))
  }
}

const getAccesRouterList = (routes, rules) => {
  return routes.filter(item => {
    const itemName = item.name
    if (rules.some(items => {
      // console.log(items)
      return items === itemName
    })) {
      if (item.children) item.children = getAccesRouterList(item.children, rules)
      return true
    } else return false
  })
  // console.log(routes)
}

const actions = {
  concatRoutes ({
    commit
  }, rules) {
    return new Promise((resolve, reject) => {
      try {
        let routerList = []
        // if (Object.entries(rules).every(item => item[1])) {
        // if () {
        //   routerList = routerMap
        // } else {
        routerList = getAccesRouterList(routerMap, rules)
        // }
        commit('CONCAT_ROUTES', routerList)
        resolve(state.routers)
      } catch (err) {
        reject(err)
      }
    })
  }
}

export default {
  state,
  mutations,
  actions
}
